/*
 *    Copyright 2014 Sam Y Ge
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.strx;

import java.util.Stack;

/**
 * 标签栈。
 * 
 * 增加路径信息
 * 
 * @author <a href="mailto:samuel.y@foxmail.com">Sam Y Ge</a>
 */
class TagStack {
	/* 内部栈容器 */
	private Stack<Tag> innerStack = new Stack<Tag>();

	/* 路径 */
	private StringBuilder tagPath = new StringBuilder();

	/**
	 * 标签压栈
	 * 
	 * @param tag
	 *            预压入栈顶标签
	 * @return 参数自身
	 */
	Tag push(Tag tag) {
		if (!innerStack.isEmpty()) {
			tagPath.append('.');
		}
		tagPath.append(tag.getName());

		return innerStack.push(tag);
	}

	/**
	 * 标签出栈
	 * 
	 * @return 栈顶标签
	 */
	synchronized Tag pop() {
		Tag top = innerStack.pop();
		int start = tagPath.lastIndexOf(".");
		int end = tagPath.length();
		if (-1 == start) {
			start = 0;
		}
		tagPath.delete(start, end);

		return top;
	}

	/**
	 * 获取栈顶元素，但不弹出
	 * 
	 * @return 栈顶元素
	 */
	synchronized Tag peek() {
		return innerStack.peek();
	}

	/**
	 * 判定是否为空栈
	 * 
	 * @return 如果栈中没有标签，则返回true，否则返回false
	 */
	boolean empty() {
		return innerStack.empty();
	}

	/**
	 * 获取栈的大小
	 * 
	 * @return 栈的大小
	 */
	int size() {
		return innerStack.size();
	}

	/**
	 * 获取当前路径。
	 * 
	 * 路径是以"."分隔的字符串
	 * 
	 * @return 路径
	 */
	String path() {
		return tagPath.toString();
	}

	/**
	 * 清除标签栈
	 */
	void clean() {
		innerStack.clear();
	}

}
